<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use App\Core\DB;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use App\Exception\HttpResponseException;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        //回滚数据库未提交的事务
        $transactionLevel = DB::transactionLevel();
        if ($transactionLevel > 0) {
            while ($transactionLevel > 0) {
                DB::rollBack();
                $transactionLevel -- ;
            }
        }

        if ( ! ($throwable instanceof HttpResponseException)) {
            $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
            $this->logger->error($throwable->getTraceAsString());
            return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
        } else {
            $message = getResponseData($throwable->getMessage(), '', $throwable->getCode());
            $this->stopPropagation();
            return $response->withStatus(200)->withBody(
                new SwooleStream(json_encode($message, JSON_UNESCAPED_UNICODE)));
        }
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
